package com.coincalf.framework.security;

import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author qiang
 */
@Component
public class ServletContextHolder {

    private static final String SESSION_KEY = "sessions:";

    public static HttpServletRequest getRequest() {
        try{
            return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        }catch(Exception e){
            return null;
        }
    }

    public static String getCookie(String name) {
        if (Strings.isNullOrEmpty(name)) {
            return null;
        }
        HttpServletRequest request = getRequest();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static UserDetails getPrincipal() {
        HttpServletRequest request = getRequest();
        String authorization = request.getHeader("Authorization");
        if (Optional.ofNullable(authorization).isPresent()) {
            String username = new JwtToken().getUsernameFromToken(authorization);
            return new UserDetails()
                    .setUsername(username);
        }
        return null;
    }

    public static String userAgent() {
        HttpServletRequest request = getRequest();
        String userAgent = request.getHeader("user-agent");
        return userAgent;
    }

    public static String remoteAddress() {
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("PRoxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        ServletContextHolder.stringRedisTemplate = stringRedisTemplate;
    }

    private static StringRedisTemplate stringRedisTemplate;
}